﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Lg.Core.EFHelper
{
    public class Copyer
    {
        /// <summary>
        /// 从 target实体中获取与source实体中相同属性名称且类型一致的属性值并赋值给source属性
        /// </summary>
        /// <typeparam name="S">源类型，要赋值的类型</typeparam>
        /// <typeparam name="T">目标类型，要复制的对像</typeparam>
        /// <param name="source">源类型实体</param>
        /// <param name="target">目标类型实体</param>
        /// <returns></returns>
        public static async Task<string> CopyChangesAsync<S,T>(S source, T target) where S:notnull where T : notnull
        {
            return await Task.Run(() =>
            {
                List<string> changes = new List<string>();
                PropertyInfo[] _oPropertyInfos = source.GetType().GetProperties();
                PropertyInfo[] _tPropertyInfos = target.GetType().GetProperties();
                foreach(var p in _oPropertyInfos)
                {
                    var tpi=_tPropertyInfos.FirstOrDefault(x=>x.Name==p.Name&&x.PropertyType==p.PropertyType);
                    if (tpi != null)
                    {
                        var tValue=tpi.GetValue(target);
                        var oValue=p.GetValue(source);
                        if(tValue != null&&tValue.ToString()!=oValue?.ToString())
                        {
                            changes.Add($"{p.Name}:[{oValue}=>{tValue}]");
                            p.SetValue(source, tValue, null );
                        }

                    }
                }
                return string.Join(',', changes);
            });
           
        }
    }
}
